<template>
	<view class="login">
		<view class="weixinLogin" v-if="loginType == 1">
			<view class="imgBox">
				<image src="@/static/images/logo.png" mode=""></image>
			</view>
			<view class="loginBox">
				<view class="txtBox">
					<view>德云祥优选 申请获取以下权限</view>
					<view>获得你的公开信息</view>
				</view>
				<button class="yellow_btn mar-bottom-20" @click="wxGetUserInfo">微信授权登录</button>
				<button class="yellow_btn" open-type="getPhoneNumber"
					@getphonenumber="decryptPhoneNumber">手机一键登录</button>
			</view>
		</view>
		<view class="bindPhoneBox" v-if="loginType == 2">
			<view class="fn-sz-56 fn-cl-333333">您好,</view>
			<view class="fn-sz-32 fn-cl-333333 mar-bottom-60">请绑定手机号码</view>
			<view class="input_number_box"><input type="text" v-model="mobile" placeholder="请输入手机号" /></view>
			<view class="input_number_smscode_box">
				<input type="text" v-model="smsCode" placeholder="请输入验证码" />
				<view class="fn-sz-24 fn-cl-333333" @tap="getCode">{{ tips }}</view>
			</view>
			<button class="yellow_btn" @click="bindPhone">绑定</button>
		</view>
		<u-toast ref="uToast"></u-toast>
		<u-code :seconds="seconds" ref="uCode" @change="codeChange"></u-code>
	</view>
</template>

<script>
	export default {
		name: 'login',
		components: {},
		data() {
			return {
				userInfo: '',
				fromDetail: false,
				detailQuery: {},
				smsCode: '',
				mobile: '',
				loginType: 1, //1是授权登录，2是验证码绑定手机号
				tips: '',
				seconds: 60
			};
		},
		onLoad(options) {
			console.log(options);

			//如果检查opneId（token），用户是登录了的，就跳转到首页
			// if (uni.getStorageSync("openId") != "") {
			//     this.$mRouter.switchTab({
			//         route: this.$mRoutesConfig.index,
			//         query: {},
			//     });
			// }
			//如果用户是从详情页跳转过来的，则记录下商品id,等下给人跳回去
			// if (options.pro_id) {
			//     this.fromDetail = true;
			//     this.detailQuery = options;
			// } else {
			//     this.fromDetail = false;
			// }
		},
		methods: {
			decryptPhoneNumber(val) {
				console.log(val, '档期');
				if (val.detail.errMsg == 'getPhoneNumber:ok') {
					this.$api.miniPhoneLogin({
						code: val.detail.code
					}).then(res => {
						this.getUserFn(res.data);
					})
				} else {
					uni.showModal({
						title: '提示',
						content: '您已拒绝授权，请重新点击并授权',
						success(res) {
							console.log('showModal确定');
						}
					});
				}

			},
			getUserFn(data) {
				this.$auth.handleLogin(data);
				this.getMemberInfo().then(res => {
					let jumpPage = uni.getStorageSync(
						'jumpPage');
					if (jumpPage && jumpPage != '/pages/login/login') {
						console.log(jumpPage.indexOf('?'),
							jumpPage, 'gagaga');
						if (jumpPage.indexOf('?') != -1) {
							uni.redirectTo({
								url: jumpPage
							});
						} else {
							uni.switchTab({
								url: jumpPage
							});
						}

					} else {
						uni.switchTab({
							url: '/pages/shop/shop'
						});
					}
				});
			},
			debounceLogin() {
				this.debounce(this.wxGetUserInfo, 2000);
			},
			codeChange(text) {
				this.tips = text;
			},

			getCode() {
				const regex = /^1[3-9]\d{9}$/;
				if (regex.test(this.mobile)) {
					if (this.$refs.uCode.canGetCode) {
						uni.showLoading({
							title: '正在获取验证码'
						});
						this.$api
							.getSmsCode({
								event: 'bind',
								mobile: this.mobile
							})
							.then(res => {
								uni.hideLoading();
								uni.$u.toast('验证码已发送');
								this.$refs.uCode.start();
							});
					} else {
						uni.$u.toast('倒计时结束后再发送');
					}
				} else {
					this.$helper.toast('请输入正确的手机号！');
				}
			},
			bindPhone() {
				let p_mid = uni.getStorageSync('p_mid');
				let params = {
					oauth_id: this.oauth_id,
					mobile: this.mobile,
					sms_code: this.smsCode
				};
				if (p_mid) {
					params.p_mid = p_mid;
				}
				this.$api.bindPhoneLogin(params).then(rex => {
					this.$helper.toast(rex.msg);
					if (rex.data.token) {
						this.$auth.handleLogin(rex.data);
						let jumpPage = uni.getStorageSync('jumpPage');
						if (jumpPage) {
							console.log(jumpPage.indexOf('?'), jumpPage, 'gagaga');
							if (jumpPage.indexOf('?') != -1) {
								uni.redirectTo({
									url: jumpPage
								});
							} else {
								uni.switchTab({
									url: jumpPage
								});
							}

						} else {
							uni.switchTab({
								url: '/pages/shop/shop'
							});
						}

					}
				});
			},
			wxGetUserInfo() {
				let that = this;
				wx.getUserProfile({
					desc: '获取用户头像名字',
					success: res => {
						console.log('授权登录信息', res);
						let userInfo = JSON.parse(res.rawData);
						console.log(userInfo, '登录信息');
						uni.login({
							success: function(_res) {
								console.log(_res, '登录信息');
								let code = _res.code;
								console.log(code, 'code');
								that.$api.wxLogin({
									code,
									nickname: userInfo.nickName
								}).then(resh => {
									console.log(resh, '登录情况');
									if (resh.data.token) {
										that.getUserFn(resh.data);
									} else {
										that.loginType = 2;
										that.oauth_id = resh.data.oauth_id;
									}
								});
							}
						});
					}
				});
				// let that = this;
			},
			getMemberInfo() {
				return new Promise((reslove, reject) => {
					this.$api.getMemberInfo().then(res => {
						console.log(res, '获取用户信息');
						if (res.code == 1) {
							this.userInfo = res.data;
							uni.setStorageSync('userInfo', res.data);
							reslove();
						}
					});
				});
			},
			debounce(func, wait) {
				let timer;
				return function() {
					let context = this; // 这边的 this 指向谁?
					let args = arguments; // arguments中存着e

					if (timer) clearTimeout(timer);

					let callNow = !timer;

					timer = setTimeout(() => {
						timer = null;
					}, wait);

					if (callNow) func.apply(context, args);
				};
			}
		}
	};
</script>

<style scoped lang="scss">
	.login {
		width: 100%;
		background: white;

		min-height: 80vh;

		.loginBox {
			text-align: center;
		}

		.weixinLogin {
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;
		}

		.imgBox {
			height: 200upx;
			width: 100%;
			display: flex;
			align-content: center;
			justify-content: center;
			padding-top: 66upx;

			image {
				width: 136upx;
				height: 136upx;
				border-radius: 50%;
			}
		}

		.txtBox {
			padding: 0 54upx;
			display: flex;
			flex-direction: column;
			margin-bottom: 200rpx;

			view {
				font-size: 30upx;
				color: #000;
				padding-bottom: 14upx;
			}

			view:nth-of-type(3) {
				color: #999;
				padding-top: 58upx;
			}
		}

		.btn {
			width: 640upx;
			height: 78upx;
			background: #10ca8f;
			border-radius: 39upx;
			color: #fff;
			text-align: center;
			justify-content: center;
			line-height: 78upx;
			font-size: 28upx;
			border: none;
			margin-top: 80upx;
		}

		.bindPhoneBox {
			padding: 48rpx 75rpx;

			.input_number_box {
				border-bottom: 1rpx solid #eeeeee;
				margin-bottom: 50rpx;
				padding-bottom: 20rpx;

				input {
					font-size: 32rpx;
					color: #333;
				}
			}

			.input_number_smscode_box {
				display: flex;
				border-bottom: 1rpx solid #eeeeee;
				margin-bottom: 50rpx;
				justify-content: space-between;
				margin-bottom: 100rpx;
				padding-bottom: 20rpx;

				input {
					font-size: 32rpx;
					color: #333;
				}
			}
		}
	}
</style>